import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function Home() {
  const location = useLocation();

  useEffect(() => {
    // 保存跳转前的位置
    const scrollPosition = window.scrollY;
    sessionStorage.setItem('homeScrollPosition', scrollPosition.toString());
    console.log('Home: Scroll position saved', scrollPosition);
  }, [location]);

  useEffect(() => {
    // 监听路由变化，恢复滚动位置
    if (location.action === 'POP') {
      const scrollPosition = sessionStorage.getItem('homeScrollPosition');
      console.log('Home: Scroll position restored', scrollPosition);
      window.scrollTo(0, scrollPosition ? parseInt(scrollPosition, 10) : 0);
    }
  }, [location]);

  return (
    <div>
      <h1>Home Page</h1>
      <p>Scroll down...</p>
      {Array.from({ length: 100 }, (_, i) => (
        <p key={i}>Item {i + 1}</p>
      ))}
    </div>
  );
}

export default Home;